package com.campuscrowdsourcing.server.aspect;

import com.campuscrowdsourcing.server.annotation.LoginCheck;
import com.campuscrowdsourcing.server.common.constant.CacheConst;
import com.campuscrowdsourcing.server.common.constant.HttpStatus;
import com.campuscrowdsourcing.server.common.constant.RoleConst;
import com.campuscrowdsourcing.server.common.expection.ServiceException;
import com.campuscrowdsourcing.server.domain.entity.User;
import com.campuscrowdsourcing.server.domain.model.LoginUser;
import com.campuscrowdsourcing.server.utils.RedisUtil;
import com.campuscrowdsourcing.server.utils.RequestUtil;
import io.lettuce.core.support.caching.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 权限校验切面
 *
 * @author XinYuan Zhao
 * @since 2023/1/25
 */

@Aspect
@Component
@Slf4j
public class LoginCheckAspect {

    @Resource
    private RedisUtil redisUtil;

    @Around("@annotation(loginCheck)")
    public Object around(ProceedingJoinPoint joinPoint, LoginCheck loginCheck)throws Throwable {
        User user = redisUtil.getCacheObject(CacheConst.LOGIN_USER_KEY + RequestUtil.getCurrentUserId());
        if (user == null) {
            throw new ServiceException("权限不足");
        }
        // 用户权限为 1，接口所需权限不为 1则返回
        if (loginCheck.value() != RoleConst.ROLE_USER && user.getUserRole() >= RoleConst.ROLE_USER) {
            throw new ServiceException(HttpStatus.FORBIDDEN, "权限不足");
        }
        return joinPoint.proceed();
    }
}
